package com.kevinxiaoge.ruoli.utils;

import com.kevinxiaoge.ruoli.annotation.Column;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;

/**
 * @author chengyuanyuan
 */
public class AnyUtils {
    //-Xms 设置初始化内存分配大小
    //-Xmx 设置最大分配内存
    //-XX:+PrintGCDetails 打印GC垃圾回收信息
    //-XX:+HeapDumpOnOutOfMemoryError   oom dump
    //-Xms10m -Xmx80m -XX:+HeapDumpOnOutOfMemoryError

    private final static String PATTERN = "yyyy-MM-dd HH:mm:ss";

    /**
     * 将Map集合中的值设置到javabean中去，map中的key与javabean中字段的注解中的值需要相同
     *
     * @param tClass
     * @param targetMap
     * @param <T>
     * @return
     */
    public static <T> T convertMapToBean(Class<T> tClass, Map<String, Object> targetMap) {
        T instance = null;
        try {
            instance = tClass.newInstance();
            if (CollectionUtils.isEmpty(targetMap)) {
                return instance;
            }
            Field[] declaredFields = tClass.getDeclaredFields();
            if (declaredFields.length > 0) {
                for (int i = 0; i < declaredFields.length; i++) {
                    Field field = declaredFields[i];
                    field.setAccessible(true);
                    if (field.isAnnotationPresent(Column.class)) {
                        Column column = field.getAnnotation(Column.class);
                        String value = column.value();
                        Set<String> keySet = targetMap.keySet();
                        for (String key : keySet) {
                            if (key.equals(value)) {
                                field.set(instance, targetMap.get(key));
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return instance;
    }

    public static String simpleDateFormat(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(PATTERN);
        return dateFormat.format(date);
    }
}
